package com.zsix.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zsix.system.mapper.SqlMapper;
import com.zsix.system.mapper.formComponentsMapper.FormEntityMapper;
import com.zsix.system.mapper.formComponentsMapper.FormMenuMapper;
import com.zsix.system.mapper.formComponentsMapper.FormSortEntityMapper;
import com.zsix.system.mapper.menu.MenuMapper;
import com.zsix.system.mapper.taskAssigneeMapper.GenerWorkMapper;
import com.zsix.system.service.IFormMapService;
import com.zsix.system.service.manager.FormManager;
import com.zsix.system.strategy.formMenu.FormMenuContext;
import com.zsix.system.strategy.formMenu.FormMenuStrategy;
import com.zsix.common.dto.controllerParams.FormDataValue;
import com.zsix.common.entity.formComponents.FormEntity;
import com.zsix.common.entity.formComponents.FormMenuEntity;
import com.zsix.common.entity.formComponents.FormSortEntity;
import com.zsix.common.entity.menu.MenuEntity;
import com.zsix.common.entity.taskAssignee.GenerWork;
import com.zsix.common.util.ListUtils;
import com.zsix.common.util.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class FormMapServiceImpl implements IFormMapService {
    @Autowired
    private FormEntityMapper formEntityMapper;
    @Autowired
    private FormMenuMapper formMenuMapper;
    @Autowired
    private FormSortEntityMapper formSortEntityMapper;
    @Autowired
    private GenerWorkMapper generWorkMapper;
    @Autowired
    private FormMenuContext formMenuContext;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private FormManager iFormManager;
    @Autowired
    private SqlMapper sqlMapper;
    @Value("spring.datasource.druid.master.name")
    private String dataSourceName;

    /**
     * 获取表单列表
     * @param formEntity
     * @return
     */
    @Override
    public List<FormEntity> formList(FormEntity formEntity){
        List<FormEntity> formList = formEntityMapper.formList(formEntity.getName(),formEntity.getFormSort());
        return formList;
    }

    /**
     * 获取表单应用列表
     * @param formEntity
     * @return
     */
    @Override
    public List<FormMenuEntity> formApplicationList(FormMenuEntity formEntity){
        List<FormMenuEntity> formList = formMenuMapper.formApplicationList(formEntity);
        return formList;
    }
    @Override
    /**
     * 设置表单表单
     * @param formEntity
     * @return
     */
    public String setFormMenu(FormMenuEntity formEntity){
        FormMenuStrategy formMenuStrategy=formMenuContext.getService(formEntity.getApplicationType());
        if(formEntity.getApplicationType().equals("1"))
            formMenuStrategy=formMenuContext.getService("0");
        return formMenuStrategy.setFormMenu(formEntity);
    }

    /**
     * 获取表单菜单详情
     * @param id
     * @return
     */
    @Override
    public FormMenuEntity getFormAppSetting(String id){
        FormMenuEntity formMenuEntity=formMenuMapper.getFormAppSetting(id);
        MenuEntity menu=menuMapper.getMenu(formMenuEntity.getId());
        formMenuEntity.setMenu(menu);
        return formMenuEntity;
    }

    /**
     * 根据sql获取字段列表
     * @return
     */
    @Override
    public List<HashMap<String,Object>> getKeysBySql(String sql){
        JSONObject jsonObject= JSON.parseObject(sql);
        Map<String,Object> map=sqlMapper.single(jsonObject.getString("keySql"),null);
        List<HashMap<String,Object>> hashMapList=new ArrayList<>();
        Set<String> keySet=map.keySet();
        for (String key : keySet) {
            HashMap<String,Object> hashMap=new HashMap<>();
            hashMap.put("id",key);
            hashMap.put("label","");
            hashMap.put("compType","");
            hashMapList.add(hashMap);
        }
        return hashMapList;
    }
    /**
     * 删除表单应用
     * @param formMenuEntity
     * @return
     */
    @Override
    public String depeteFormMenu(FormMenuEntity formMenuEntity){
        if(formMenuEntity.getApplicationType().equals("1"))
            formMenuEntity.setApplicationType("0");
        FormMenuStrategy formMenuStrategy=formMenuContext.getService(formMenuEntity.getApplicationType());
        return formMenuStrategy.depeteFormMenu(formMenuEntity);
    }
    /**
     * 获取表单树
     * @return
     */
    @Override
    public List<FormEntity> getFormTree(){
        return formEntityMapper.getFormTree();
    }
    @Override
    public List<FormEntity> getFormTreeByAdd(){
        return formEntityMapper.getFormTreeByAdd();
    }
    @Override
    public FormEntity getFormEntity(String id){
        try{
            FormEntity formEntity=formEntityMapper.formEntity(id);
            return formEntity;
        }
        catch (Exception ex){
            return new FormEntity();
        }
    }
    @Override
    public String addForm(String id,String name,String createTime,String formSort,String form_event
            ,String form_event_link,String form_data_table,String form_sub_tables,String form_json){
        try{
            FormEntity formEntity=new FormEntity();
            formEntity.setId(id);
            formEntity.setName(name);
            formEntity.setCreateTime(createTime);
            formEntity.setFormSort(formSort);
            formEntity.setForm_event(form_event);
            formEntity.setForm_event_link(form_event_link);
            formEntity.setForm_data_table(form_data_table);
            formEntity.setForm_sub_tables(form_sub_tables);
            formEntity.setForm_json(form_json);

            if(!StringUtils.isNull(form_json)) {
                JSONObject jsonObject=JSONObject.parseObject(form_json);
                String msg=iFormManager.createTableByJson(form_data_table,jsonObject.getString("list"),false);
                if(!msg.equals("suess")){
                    return msg;
                }
            }
            //增加表单模版
            formEntityMapper.addForm(formEntity);
            return "执行成功";
        }
        catch (Exception ex){
            return ex.getMessage().toString();
        }
    }
    /**
     * 增加/修改表单
     * @param param
     * @return
     */
    @Override
    public String editForm(JSONObject param){
        JSONObject jsonObject=JSONObject.parseObject(param.getString("viewcode"));
        JSONObject configJson=JSONObject.parseObject(jsonObject.getString("config"));

        FormEntity formEntity=getFormEntity(param.getString("formid"));
        if(formEntity==null) {
            formEntity=new FormEntity();
            formEntity.setId(param.getString("formid"));
            formEntity.setName(configJson.getString("formRef"));
            formEntity.setCreateTime(DateTime.now().toString("yyyy-MM-dd hh:mm:ss"));
            formEntity.setFormSort(configJson.getString("formSort"));
            formEntity.setForm_data_table(configJson.getString("tableName"));
            formEntity.setForm_json(param.getString("viewcode"));

            iFormManager.addForm(formEntity);
        }
        else{
            formEntity.setForm_json(param.getString("viewcode"));
            iFormManager.updateForm(formEntity);
        }


        return "设置成功";
    }
    @Override
    public String deleteForm(String id){
        try{
            formEntityMapper.deleteForm(id);
            return "执行成功";
        }
        catch (Exception ex){
            return ex.getMessage().toString();
        }
    }
    @Override
    public String updateForm(String id,String name,String createTime,String formSort,String form_event
            ,String form_event_link,String form_data_table,String form_sub_tables,String form_json){
        try{
            FormEntity formEntity=new FormEntity();
            formEntity.setId(id);
            formEntity.setName(name);
            formEntity.setCreateTime(createTime);
            formEntity.setFormSort(formSort);
            formEntity.setForm_event(form_event);
            formEntity.setForm_event_link(form_event_link);
            formEntity.setForm_data_table(form_data_table);
            formEntity.setForm_sub_tables(form_sub_tables);
            formEntity.setForm_json(form_json);
            //更新模版
            formEntityMapper.updateForm(formEntity);

            //判断是否已经存在该表
            int isTableExist=formEntityMapper.isTableExist(form_data_table.toLowerCase(),dataSourceName);
            if(isTableExist>0) {
                iFormManager.AlterTableAddField(form_data_table,form_json);
            }
            else{
                JSONObject jsonObject=JSONObject.parseObject(form_json);
                String msg=iFormManager.createTableByJson(form_data_table,jsonObject.getString("list"),false);
                if(!msg.equals("suess")){
                    return msg;
                }
            }
            return "执行成功";
        }
        catch (Exception ex){
            return ex.getMessage().toString();
        }
    }
    @Override
    public List<FormSortEntity> formSortList(){
        try{
            List<FormSortEntity> formSortList=formSortEntityMapper.formSortList();
            //2、组装树形结构
            List<FormSortEntity> newList = formSortList.stream()
                    .filter(t -> t.getParentNo().equals("0") )
                    .map((menu) -> {
                        menu.setChildren(iFormManager.getChildren(menu,formSortList));
                        return menu;
                    })
                    .collect(Collectors.toList());
            return newList;
        }
        catch (Exception ex){
            return new ArrayList<>();
        }
    }
    @Override
    public FormSortEntity getFormSort(String id){
        try{
            FormSortEntity formSortEntity=formSortEntityMapper.formSort(id);
            return formSortEntity;
        }
        catch (Exception ex){
            return new FormSortEntity();
        }
    }
    @Override
    public String addFormSort(String id,String name,String parentNo){
        try{
            FormSortEntity formSortEntity=new FormSortEntity();
            formSortEntity.setId(id);
            formSortEntity.setName(name);
            formSortEntity.setParentNo(parentNo);
            formSortEntityMapper.addFormSort(formSortEntity);
            return "执行成功";
        }
        catch (Exception ex){
            return ex.getMessage().toString();
        }
    }
    @Override
    public String deleteFormSort(String id){
        try{
            formSortEntityMapper.deleteFormSort(id);
            return "执行成功";
        }
        catch (Exception ex){
            return ex.getMessage().toString();
        }
    }
    @Override
    public String updateFormSort(String id,String name,String parentNo){
        try{
            FormSortEntity formSortEntity=new FormSortEntity();
            formSortEntity.setId(id);
            formSortEntity.setName(name);
            formSortEntity.setParentNo(parentNo);
            formSortEntityMapper.updateFormSort(formSortEntity);
            return "执行成功";
        }
        catch (Exception ex){
            return ex.getMessage().toString();
        }
    }
    /**
     * 保存表单数据
     * @param formDataValue
     * @return
     */
    @Override
    public String saveFormDataJson(FormDataValue formDataValue){
        String guid=formDataValue.getId();
        JSONObject config=JSONObject.parseObject(formDataValue.getMapJson());
        String mainTable=config.getString("tableName");
        String sql="select id from "+mainTable+" where id='"+guid+"'";
        Map<String,Object> map=sqlMapper.single(sql,null);

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username=authentication.getName();
        try{
            GenerWork generWork=new GenerWork();
            if(!StringUtils.isNull(guid)&&!guid.equals("0")&&map!=null){
                generWork=generWorkMapper.generWork(guid);
                //如果为空，可能是外部表单传过来的businessKey
                if(generWork==null){
                    generWork=new GenerWork();
                    generWork.setId(guid);
                    if(formDataValue.getForm_type().equals("1")){
                        //generWork.setForm_map(formDataValue.getForm_url());
                    }
                    else {
                        generWork.setFormMap(formDataValue.getMapJson());
                        generWork.setData_json(formDataValue.getDataJson());
                    }
                    generWork.setStarter(username);
                    generWork.setCreatetime(DateTime.now().toString("yyyy-MM-dd hh:mm:ss"));
                    generWork.setProcesskey(formDataValue.getProcessKey());
                    generWorkMapper.insertGenerWork(generWork);
                }
                else {
                    generWork.setId(guid);
                    if (formDataValue.getForm_type().equals("1")) {
                        //generWork.setMap_json(formDataValue.getForm_url());
                    } else {
                        generWork.setFormMap(formDataValue.getMapJson());
                        generWork.setData_json(formDataValue.getDataJson());
                    }
                    generWork.setProcesskey(formDataValue.getProcessKey());
                    generWorkMapper.updateGenerWork(generWork);
                }
            }
            else {
                guid=UUID.randomUUID().toString();
                generWork.setId(guid);
                if(formDataValue.getForm_type().equals("1")){
                    //generWork.setMap_json(formDataValue.getForm_url());
                }
                else {
                    generWork.setFormMap(formDataValue.getMapJson());
                    generWork.setData_json(formDataValue.getDataJson());
                }
                generWork.setProcesskey(formDataValue.getProcessKey());
                generWork.setStarter(username);
                generWork.setCreatetime(DateTime.now().toString("yyyy-MM-dd hh:mm:ss"));
                generWorkMapper.insertGenerWork(generWork);
            }
            return guid;
        }
        catch (Exception ex){
            return "error";
        }
    }
    @Override
    public GenerWork getGenerWork(String id){
        GenerWork generWork=generWorkMapper.generWork(id);
        return generWork;
    }

    @Override
    public GenerWork getGenerWorkByLink(String linkId,String formKey){
        FormEntity formEntity=formEntityMapper.formEntity(formKey);
        GenerWork generWork=new GenerWork();
        String sql="select id from "+formEntity.getForm_data_table()+"  where fk_id='"+linkId+"'";
        Map<String,Object> map=sqlMapper.single(sql,null);
        if(map==null){
            generWork=new GenerWork();
            generWork.setMap_json(formEntity.getForm_json());
        }
        else{
            generWork=generWorkMapper.generWork(map.get("id").toString());
            generWork.setMap_json(formEntity.getForm_json());

            if(generWork==null){
                generWork=new GenerWork();

            }
        }
        return generWork;
    }

    @Override
    public GenerWork getGenerWorkByFKId(String fk_id,String formKey){
        FormEntity formEntity=formEntityMapper.formEntity(formKey);
        GenerWork generWork=new GenerWork();
        String sql="select id from "+formEntity.getForm_data_table()+"  where id='"+fk_id+"'";
        Map<String,Object> map=sqlMapper.single(sql,null);
        if(map==null){
            generWork=new GenerWork();
            generWork.setMap_json(formEntity.getForm_json());
        }
        else{
            generWork=generWorkMapper.generWork(map.get("id").toString());
            generWork.setMap_json(formEntity.getForm_json());

            if(generWork==null){
                generWork=new GenerWork();

            }
        }
        return generWork;
    }

    /**
     * 删除应用数据
     * @param frmId
     * @param ids
     * @return
     */
    @Override
    public String deleteGenerWork(String frmId,String ids){
        String msg="";
        try{
            List<String> idList=new ArrayList<>();
           String str= StringUtils.removeEnd(ids,",");
           if(str.contains(",")){
               for(String item:str.split(",")){
                   idList.add(item);
               }
           }
           else
               idList.add(str);
           //删除记录数据
            generWorkMapper.deleteGenerWork(idList);
            if(!StringUtils.isNull(frmId)) {
                //删除主表数据
                FormEntity formEntity = formEntityMapper.formEntity(frmId);
                generWorkMapper.deleteFrmData(formEntity.getForm_data_table(), idList);

                //删除子表数据
                List<String> subTables=new ArrayList<>();
                JSONObject jsonObject=JSONObject.parseObject(formEntity.getForm_json());
                JSONArray listJson = JSONArray.parseArray(jsonObject.getString("list"));
                if(ListUtils.isNotNull(listJson)){
                    //如果是子表
                    listJson.stream().map(var -> (JSONObject) var).forEach(object -> {
                        if (object.get("compType").equals("dynamicTable")) {
                            //遍历相关的子
                            String formChildName = object.get("id").toString();//子表的表
                            subTables.add(formChildName);
                        }
                        if(object.getString("compType").equals("row")){
                            JSONArray childList = JSONArray.parseArray(object.getString("columns"));
                            for(int i = 0; i < childList.size(); i++){
                                JSONObject children = childList.getJSONObject(i);
                                JSONArray childrenList=JSONArray.parseArray(children.getString("list"));
                                for(int k=0;k<childrenList.size();k++){
                                    JSONObject rowlist=childrenList.getJSONObject(k);
                                    //保存附件
                                    if (rowlist.get("compType").equals("dynamicTable")) {
                                        //遍历相关的子
                                        String formChildName = rowlist.get("id").toString();//子表的表
                                        subTables.add(formChildName);
                                    }
                                }
                            }
                        }
                    });
                }
                if(subTables.size()>0) {
                    for (String subTable : subTables) {
                        generWorkMapper.deleteFrmSubData(subTable, idList);
                    }
                }
            }
            msg="suess";
            return msg;
        }
        catch (Exception ex){
            return ex.getMessage();
        }
    }
}
